package com.ycx.furns.web;

import com.google.gson.Gson;
import com.ycx.furns.entity.Cart;
import com.ycx.furns.entity.Furn;
import com.ycx.furns.entity.Order;
import com.ycx.furns.service.FurnService;
import com.ycx.furns.service.impl.FurnServiceImpl;
import com.ycx.furns.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/cartServlet")
public class CartServlet extends BasicServlet{
    FurnService furnService = new FurnServiceImpl();

    protected void updateCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        int num = DataUtils.parseInt(req.getParameter("num"), 1);
        if(cart != null){
            cart.update(id, num);
        }
        resp.sendRedirect(req.getHeader("referer"));
    }

    protected void clearItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        if(cart != null){

            cart.clear();
        }
        resp.sendRedirect(req.getHeader("referer"));
    }

    protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        if(cart != null){

            cart.deleteItem(id);
        }
        resp.sendRedirect(req.getHeader("referer"));
    }

    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.getFurnById(id);
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }

        if(furn != null){

            cart.addItem(new Cart.Item(id, furn.getName(), furn.getPrice(), 1, furn.getPrice(), ""));
            int totalCount = cart.getTotalCount();
            Map<String, Object> map = new HashMap<>();
            map.put("count", totalCount);
            String json = new Gson().toJson(map);
            resp.getWriter().write(json);
            System.out.println(cart.getItems());
//            resp.sendRedirect(req.getHeader("referer"));
//        req.getRequestDispatcher("/views/customer/index.jsp").forward(req, resp);
        }else {
//            resp.sendRedirect(req.getHeader("referer"));

        }
    }
}
